package com.joysuch.wwyt.openapi.services.serviceV1.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.escape.ArrayBasedUnicodeEscaper;
import com.google.common.io.ByteStreams;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.dto.BpStorageTankAreaDto;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.core.bean.BaseUserFindAllBean;
import com.joysuch.wwyt.core.common.util.PinYinUtils;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.*;
import com.joysuch.wwyt.core.entity.dsl.QBaseLoginAccount;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.enums.UserRoleTypes;
import com.joysuch.wwyt.core.repository.*;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BaseLoginAccountService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dzhapi.bean.*;
import com.joysuch.wwyt.dzhapi.dto.BuildDataDto;
import com.joysuch.wwyt.dzhapi.exception.ApiException;
import com.joysuch.wwyt.dzhapi.mapper.*;
import com.joysuch.wwyt.edu.entity.EduCourse;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.openapi.constants.ApiCode;
import com.joysuch.wwyt.openapi.constants.ApiStatus;
import com.joysuch.wwyt.openapi.controllers.controllerV1.req.ApiV1BaseUserAddReq;
import com.joysuch.wwyt.openapi.controllers.controllerV1.req.ApiV1BaseUserReq;
import com.joysuch.wwyt.openapi.controllers.controllerV1.req.ApiV1BaseUserUpdateReq;
import com.joysuch.wwyt.openapi.controllers.controllerV1.vo.ApiPagePropertyDataVo;
import com.joysuch.wwyt.openapi.controllers.controllerV1.vo.ApiResultData;
import com.joysuch.wwyt.openapi.controllers.controllerV1.vo.ApiV1BaseUserVo;
import com.joysuch.wwyt.openapi.exception.ApiV1ExceptionCodeMsg;
import com.joysuch.wwyt.openapi.services.serviceV1.ApiV1BaseUserService;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import com.joysuch.wwyt.util.StringUtil;
import com.querydsl.core.types.ExpressionUtils;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: JamesZY
 * @date: 2021/8/23
 * @description:
 */
@Slf4j
@Service
public class ApiV1BaseUserServiceImpl implements ApiV1BaseUserService {
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BpJobDao jobDao;
    @Autowired
    private BpDepartDao departDao;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private BaseLoginAccountService baseLoginAccountService;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BpCertificateDao certificateDao;
    @Autowired
    private BaseRoleDao baseRoleDao;
    @Autowired
    private BaseRoleUserLoginRoleDao baseRoleUserLoginRoleDao;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BaseTypeGroupDao baseTypeGroupDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private BpWorkTypeDao bpWorkTypeDao;
    @Autowired
    private BpEnterpriseInfoDao infoDao;
    @Autowired
    private ApiBpDepartMapper departMapper;
    @Autowired
    private ApiBpJobMapper jobMapper;
    @Autowired
    private ApiBaseUserMapper userMapper;
    @Autowired
    private ApiBaseLoginAccountMapper loginAccountMapper;
    @Autowired
    private ApiBaseImageRepositoryMapper imageRepositoryMapper;
    @Autowired
    private ApiBaseConfigMapper configMapper;
    @Autowired
    private ApiBpContractorStaffMapper contractorStaffMapper;
    @Autowired
    private ApiBpEnterpriseInfoMapper infoMapper;
    @Autowired
    private ApiBaseTypeGroupItemMapper groupItemMapper;
    @Autowired
    private ApiBpWorkTypeMapper workTypeMapper;
    @Autowired
    private ApiBpCertificateMapper certificateMapper;
    @Autowired
    private ApiBaseRoleMapper roleMapper;
    @Autowired
    private ApiBaseRoleUserLoginRoleMapper userLoginRoleMapper;
    @Autowired
    private ApiBaseTypeGroupItemMapper itemMapper;

    @Value("${wwyt.biz.user.account.forceSyncCodeAsLoginAccount}")
    private boolean forceSyncCodeAsLoginAccount;
    // 默认密码
    @Value("${wwyt.biz.user.account.defaultPassword}")
    private String defaultPassword;
    @Value("${wwyt.file.upload.dir}")
    private String imageUploadPath;

    @Override
    public ApiPagePropertyDataVo findAll(ApiV1BaseUserReq req, BuildDataDto buildDataDto) {
        QueryWrapper<ApiBaseUserBean> queryWrapper = new QueryWrapper<>();
//        Specification<BaseUser> specification = new Specification<BaseUser>() {
//            @SneakyThrows
//            @Override
//            public Predicate toPredicate(Root<BaseUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                List<Predicate> predicatesList = new ArrayList<>();
        if (!ObjectUtil.isEmpty(req.getUniqueId())) {
            queryWrapper.eq("unique_id", req.getUniqueId());
//                    predicatesList.add(cb.equal(root.get("uniqueId"), req.getUniqueId()));
        }
        if (!StringUtil.isEmpty(req.getRealName())) {
            queryWrapper.eq("REAL_NAME", req.getRealName());
//                    predicatesList.add(cb.equal(root.get("realName"), req.getRealName()));
        }
        if (!StringUtil.isEmpty(req.getGender())) {
            queryWrapper.eq("GENDER", req.getGender());
//                    predicatesList.add(cb.equal(root.get("gender"), req.getGender()));
        }
        if (!StringUtil.isEmpty(req.getCode())) {
            queryWrapper.eq("code", req.getCode());
//                    predicatesList.add(cb.equal(root.get("code"), req.getCode()));
        }
        if (!StringUtil.isEmpty(req.getDepartUniqueId())) {
            ApiBpDepartBean departbean = departMapper.findByUniqueId(req.getDepartUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                    BpDepart depart = departDao.findByUniqueId(req.getDepartUniqueId());
            if (ObjectUtil.isEmpty(departbean)) {
                throw new ApiV1ExceptionCodeMsg(ApiStatus.ERROR, Status.DEPART_NOT_EXIST.getCode(), Status.DEPART_NOT_EXIST.getMsg());
            }
            queryWrapper.eq("DEPART_ID", departbean.getId());
//                    predicatesList.add(cb.equal(root.get("departId"), departbean.getId()));
        }
        if (!StringUtil.isEmpty(req.getJobUniqueId())) {
            ApiBpJobBean jobBean = jobMapper.findByUniqueId(req.getJobUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                    BpJob job = jobDao.findByUniqueId(req.getJobUniqueId());
            if (ObjectUtil.isEmpty(jobBean)) {
                throw new ApiV1ExceptionCodeMsg(ApiStatus.ERROR, Status.API_V1_JOB_NOT_EXIST.getCode(), Status.API_V1_JOB_NOT_EXIST.getMsg());
            }
            queryWrapper.eq("JOB", jobBean.getId());
//                    predicatesList.add(cb.equal(root.get("job"), jobBean.getId()));
        }
        if (!ObjectUtil.isEmpty(req.getIdCardType())) {
            queryWrapper.eq("ID_CARD_TYPE", req.getIdCardType());
//                    predicatesList.add(cb.equal(root.get("idCardType"), req.getIdCardType()));
        }
        if (!StringUtil.isEmpty(req.getIdCardNo())) {
            queryWrapper.eq("ID_CARD_NO", req.getIdCardNo());
//                    predicatesList.add(cb.equal(root.get("idCardNo"), req.getIdCardNo()));
        }
        if (!StringUtil.isEmpty(req.getSn())) {
            queryWrapper.eq("sn", req.getSn());
//                    predicatesList.add(cb.equal(root.get("sn"), req.getSn()));
        }
        if (!StringUtil.isEmpty(req.getCardNumber())) {
            queryWrapper.eq("card_number", req.getCardNumber());
//                    predicatesList.add(cb.equal(root.get("cardNumber"), req.getCardNumber()));
        }
        if (!ObjectUtil.isEmpty(req.getStartUpdateTime())) {
            queryWrapper.ge("UPDATE_TIME", req.getStartUpdateTime());
//                    predicatesList.add(cb.greaterThanOrEqualTo(root.get("updateTime"), req.getStartUpdateTime()));
        }
        if (!ObjectUtil.isEmpty(req.getEndUpdateTime())) {
            queryWrapper.le("UPDATE_TIME", req.getEndUpdateTime());
//                    predicatesList.add(cb.lessThanOrEqualTo(root.get("updateTime"), req.getEndUpdateTime()));
        }
        queryWrapper.eq("TENENT_ID", buildDataDto.getTenentId());
        queryWrapper.eq("ORG_CODE", buildDataDto.getOrgCode());
        queryWrapper.eq("DELETE_FLAG", "0");
        queryWrapper.and(QueryWrapper -> QueryWrapper.isNull("state").or().eq("state", "1"));
//                query.orderBy(cb.desc(root.get("createTime")));
//                Predicate[] predicates = new Predicate[predicatesList.size()];
//                return cb.and(predicatesList.toArray(predicates));
//            }
//        };
//        PageRequest pageRequest = PageRequest.of((req.getPageNumber() - 1), req.getPageSize());
        Page<ApiBaseUserBean> page = new Page<>(req.getPageNumber(), req.getPageSize());
        userMapper.selectPage(page, queryWrapper);
//        Page<BaseUser> all = baseUserDao.findAll(specification, pageRequest);
        List<ApiV1BaseUserVo> list = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(u -> {
                ApiV1BaseUserVo b = new ApiV1BaseUserVo();
                BeanUtils.copyProperties(u, b);
                b.setAccount(username(u.getId()));
                b.setCode(u.getCode());
                b.setName(u.getRealName());
                if (ObjectUtil.isNotEmpty(u.getDepartId())) {
                    ApiBpDepartBean departBean = departMapper.selectById(u.getDepartId());
//                    Optional<BpDepart> depart = departDao.findById(u.getDepartId());
                    if (departBean != null) {
                        b.setDepartUniqueId(departBean.getUniqueId());
                        // 部门
                        b.setDepartName(departBean.getName());
                    }
                }
                if (ObjectUtil.isNotEmpty(u.getJob())) {
                    ApiBpJobBean jobBean = jobMapper.selectById(u.getJob());
//                    Optional<BpJob> job = jobDao.findById(u.getJob());
                    if (jobBean != null) {
                        b.setJobUniqueId(jobBean.getUniqueId());
                        b.setJobName(jobBean.getName());
                    }
                }
                b.setLocateSync(u.getLocateSync());
                b.setSn(u.getSn());
                b.setRole(u.getRole());
                if (u.getRole() != null) {
                    b.setRoleName(UserRoleTypes.getRoleNameByIndex(u.getRole().intValue()));
                }
                // 账号开启/关闭状态
                if (loginAccountMapper.findByBaseUser(u.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) != null) {
                    // b.setLoginShowState(baseLoginAccountDao.findByUserDetailId(u.getId()).getShowState());
                    b.setLoginShowState(loginAccountMapper.findByBaseUser(u.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()).getShowState());
                }
                b.setAlarmTemplateId(u.getAlarmTemplateId());
                b.setAlarmTemplateName(u.getAlarmTemplateName());

//                if (ObjectUtil.isNotEmpty(u.getIdCardImgId())) {
//                    ApiBaseImageRepositoryBean apiBaseImageRepositoryBean = imageRepositoryMapper.selectById(u.getIdCardImgId());
////                    Optional<BaseImageRepository> optional = baseImageRespositoryDao.findById(u.getIdCardImgId());
//                    if (apiBaseImageRepositoryBean != null) {
//                        b.setPicPath(apiBaseImageRepositoryBean.getOriginPath());
//                        String imagePath = imageUploadPath + File.separator + apiBaseImageRepositoryBean.getOriginPath();
//                        try {
//                            FileInputStream fileInputStream = new FileInputStream(imagePath);
//                            byte[] bytes = ByteStreams.toByteArray(fileInputStream);
//                            String imageBase64 = Base64.getEncoder().encodeToString(bytes);
//                            b.setImage(imageBase64);
//                        } catch (IOException e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                }
                list.add(b);
            });
        }
        ApiPagePropertyDataVo apiPagePropertyDataVo = new ApiPagePropertyDataVo();
        apiPagePropertyDataVo.setData(list);
        apiPagePropertyDataVo.setTotalElements(page.getTotal());
        apiPagePropertyDataVo.setTotalPages((int) page.getPages());
        apiPagePropertyDataVo.setPresentPage((int) page.getCurrent());
        return apiPagePropertyDataVo;
    }

    private String username(Long id) {
        QBaseLoginAccount baseLoginAccount = QBaseLoginAccount.baseLoginAccount;
        com.querydsl.core.types.Predicate predicate1 = baseLoginAccount.isNotNull();
        predicate1 = id == null ? predicate1 : ExpressionUtils.and(predicate1, baseLoginAccount.baseUser.id.eq(id));
        Iterable<BaseLoginAccount> als = baseLoginAccountDao.findAll(predicate1);

        if (als != null) {
            for (BaseLoginAccount al : als) {
                return "已有账户";
            }
        }
        return "未有账户";
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public List<ApiResultData> batchDelete(List<String> data, BuildDataDto buildDataDto) {
        List<ApiResultData> list = Lists.newArrayList();
        data.forEach(id -> {
            ApiResultData res = new ApiResultData();
            if (StringUtil.notEmpty(id)) {
                ApiBaseUserBean baseUserBean = userMapper.findByUniqueId(id, buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                BaseUser user = baseUserDao.findByUniqueId(id);
                if (baseUserBean == null) {
                    res.setUniqueId(id);
                    res.setMsg("人员不存在");
                    list.add(res);
                    return;
                }
                baseUserBean.setState(DataStateTypes.DELETE.getState());
                ApiBaseLoginAccountBean loginAccountBean = loginAccountMapper.findByBaseUser(baseUserBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                if (loginAccountBean != null) {
                    loginAccountMapper.deleteById(loginAccountBean.getId());
                }
//                baseLoginAccountDao.deleteByUserId(user.getId());
                userMapper.updateById(baseUserBean);
//                BaseUser save = baseUserDao.save(user);
                if (baseUserBean.getJob() != null) {
                    updateJobUserCount(baseUserBean.getJob(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                }
                BaseUser save = new BaseUser();
                BeanUtils.copyProperties(baseUserBean, save);
                // 同步人员
                if (isApiEmployeeSyncOpen(buildDataDto)) {
                    locateServerService.apiSyncLocateUsers(Lists.newArrayList(save), 0, buildDataDto);
                }
                res.setUniqueId(save.getUniqueId());
                res.setName(save.getRealName());
                res.setMsg("删除成功");
                list.add(res);
            }
        });
        return list;
    }

    private boolean isApiEmployeeSyncOpen(BuildDataDto dto) {
        ApiBaseConfigBean config = configMapper.findConfig(dto.getTenentId(), dto.getOrgCode(), BaseConfigCodes.LOCATE_SERVER_EMPLOYEE_SYNC_OPEN);
        return config == null ? false : "true".equalsIgnoreCase(config.getValue());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void update(ApiV1BaseUserUpdateReq req, BuildDataDto buildDataDto) throws ApiV1ExceptionCodeMsg {
//        BaseUser b = new BaseUser();
        ApiBaseUserBean baseUserBean = userMapper.findByUniqueId(req.getUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//        BaseUser user = baseUserDao.findByUniqueId(req.getUniqueId());
        if (ObjectUtil.isEmpty(baseUserBean)) {
            throw new ApiV1ExceptionCodeMsg(Status.API_V1_PEOPLE_IS_NO);
        }
        if (userMapper.countByNameExcludeSelf(req.getRealName(), baseUserBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
            throw new ApiV1ExceptionCodeMsg(Status.USER_NAME_EXIST);
        }
//        Long id = baseUserBean.getId();
        ApiBaseUserBean userBean = new ApiBaseUserBean();
        BeanUtils.copyProperties(baseUserBean, userBean);
        if (StringUtil.notEmpty(req.getRealName())) {
            userBean.setRealName(req.getRealName());
        }
        if (StringUtil.notEmpty(req.getRealName())) {
            userBean.setGender(req.getGender());
        }
        if (StringUtil.notEmpty(req.getDepartUniqueId())) {
            ApiBpDepartBean departBean = departMapper.findByUniqueId(req.getDepartUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (departBean == null) {
                throw new ApiV1ExceptionCodeMsg(Status.DEPART_NOT_EXIST);
            }
            userBean.setDepartId(departBean.getId());
        }
        if (ObjectUtil.isNotEmpty(req.getRole())) {
            userBean.setRole(req.getRole());
        }
        if (StringUtil.notEmpty(req.getWorkType())) {
            ApiBpWorkTypeBean workTypeBean = workTypeMapper.findByName(req.getWorkType(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (workTypeBean == null) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_WORKTYPE_NOTEXIST);
            }
            userBean.setWorkTypeId(workTypeBean.getId());
        }
        if (StringUtil.notEmpty(req.getOldName())) {
            userBean.setOldName(req.getOldName());
        }
//        if (StringUtil.notEmpty(req.getNationName())){
//            userBean.setNation();
//        }
        if (StringUtil.notEmpty(req.getIdCardNo())) {
            userBean.setIdCardNo(req.getIdCardNo());
        }
        if (StringUtil.notEmpty(req.getTelephone())) {
            userBean.setTelephone(req.getTelephone());
        }
        if (StringUtil.notEmpty(req.getEmail())) {
            userBean.setEmail(req.getEmail());
        }
        if (StringUtil.notEmpty(req.getNationName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getNationName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setNation(itemBean.getId());
            }
        }
        if (StringUtil.notEmpty(req.getHealthStatusName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getHealthStatusName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setHealthStatus(itemBean.getId());
            }
        }
        if (StringUtil.notEmpty(req.getIdCardName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getIdCardName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setIdCardType(itemBean.getId());
            }
        }
        if (StringUtil.notEmpty(req.getEducationName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getEducationName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setEducation(itemBean.getId());
            }
        }
        //政治面貌
        if (StringUtil.notEmpty(req.getPoliticallyName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getPoliticallyName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setPoliticallyId(itemBean.getId());
            }
        }
        //人员类型
        if (StringUtil.notEmpty(req.getPersonTypeName())) {
            ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(req.getPersonTypeName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            if (itemBean != null) {
                userBean.setPersonTypeId(itemBean.getId());
            }
        }
        //户籍
        if (StringUtil.notEmpty(req.getCensus())) {
            userBean.setCensus(req.getCensus());
        }
        //办公电话
        if (StringUtil.notEmpty(req.getOfficePhone())) {
            userBean.setOfficePhone(req.getOfficePhone());
        }
        //工龄
        if (ObjectUtil.isNotEmpty(req.getWorkAge())) {
            userBean.setWorkAge(req.getWorkAge());
        }
        //职称
        if (StringUtil.notEmpty(req.getTitle())) {
            userBean.setTitle(req.getTitle());
        }
        //职务
        if (StringUtil.notEmpty(req.getDuty())) {
            userBean.setDuty(req.getDuty());
        }
        //工作职责
        if (StringUtil.notEmpty(req.getJobDuty())) {
            userBean.setJobDuty(req.getJobDuty());
        }
        //备注
        if (StringUtil.notEmpty(req.getRemark())) {
            userBean.setRemark(req.getRemark());
        }
        //工作经历
        if (StringUtil.notEmpty(req.getJobHistory())) {
            userBean.setJobHistory(req.getJobHistory());
        }
        //	从业地
        if (StringUtil.notEmpty(req.getWork())) {
            userBean.setWork(req.getWork());
        }
        //邮箱
        if (StringUtil.notEmpty(req.getEmail())) {
            userBean.setEmail(req.getEmail());
        }
        //最高学位
        if (StringUtil.notEmpty(req.getHighestDegree())) {
            userBean.setHighestDegree(req.getHighestDegree());
        }
        //毕业学校
        if (StringUtil.notEmpty(req.getGraduateSchool())) {
            userBean.setGraduateSchool(req.getGraduateSchool());
        }
        //头像图标
        if (StringUtil.notEmpty(req.getFacePic())) {
            userBean.setFacePic(req.getFacePic());
        }
        //外部关联url
        if (StringUtil.notEmpty(req.getRefUrl())) {
            userBean.setRefUrl(req.getRefUrl());
        }
        //专业
        if (StringUtil.notEmpty(req.getMajor())) {
            userBean.setMajor(req.getMajor());
        }
        //通讯地址
        if (StringUtil.notEmpty(req.getAddress())) {
            userBean.setAddress(req.getAddress());
        }
        //邮编
        if (StringUtil.notEmpty(req.getPostcode())) {
            userBean.setPostcode(req.getPostcode());
        }
//        BeanUtils.copyProperties(req, userBean);
//        BeanUtils.copyProperties(baseUserBean, userBean);
//        userBean.setId(id);
//        BeanUtils.copyProperties(baseUserBean, b);
        if (req.getCode() != null && userMapper.countOfCodeExcludeId(req.getCode(), baseUserBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
            throw new ApiV1ExceptionCodeMsg(Status.API_V1_CODE_IS_EXIST);
        }
        userBean.setCode(req.getCode());
        if (StringUtil.notEmpty(req.getJobUniqueId())) {
            Long oldJobId = baseUserBean.getJob();
            ApiBpJobBean jobBean = jobMapper.findByUniqueId(req.getJobUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//            BpJob job = jobDao.findByUniqueId(req.getJobUniqueId());
            if (ObjectUtil.isEmpty(jobBean)) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_JOB_NOT_EXIST);
            }
            Long newJobId = jobBean.getId();
            if (!Objects.equals(oldJobId, newJobId)) {
                updateJobUserCount(oldJobId, buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                updateJobUserCount(newJobId, buildDataDto.getTenentId(), buildDataDto.getOrgCode());
            }
            userBean.setJob(newJobId);
        }
        userBean.setUpdateBy(-1L);
        userBean.setUpdateTime(new Date());
//        boolean codeChanged = false;
//        if (StringUtil.notEmpty(req.getCode())) {
//            codeChanged = !Objects.equals(req.getCode(), baseUserBean.getCode());
//        }

//        b.setId(user.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String birthday = req.getBirthday();
        String enterDate = req.getEnterDate();
        userBean.setBirthday(org.springframework.util.StringUtils.isEmpty(birthday) ? null : LocalDateTimeUtil.parseDate(birthday));
        userBean.setEnterDate(org.springframework.util.StringUtils.isEmpty(enterDate) ? null : LocalDateTimeUtil.parseDate(enterDate));
        if (req.getJoinWorkDate() != null && !req.getJoinWorkDate().isEmpty()) {
            userBean.setJoinWorkDate(LocalDateTimeUtil.parseDate(req.getJoinWorkDate()));
        } else {
            userBean.setJoinWorkDate(null);
        }
        if (req.getImage() != null) {
            userBean.setIdCardImgId(req.getImage().getId());
        }
        if (req.getCap() != null) {
            userBean.setCapId(req.getCap().getId());
        }
        if (StringUtil.notEmpty(req.getSn())) {
            userBean.setSn(req.getSn());
            if (userMapper.countBySnExcludeSelf(userBean.getSn(), userBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_USER);
            }
        }
        // 修改时确保有uniqueId
//        if (b.getUniqueId() == null) {
//            b.setUniqueId(SnowFlakeUtil.getUserId());
//        }
        userBean.setOrgCode(buildDataDto.getOrgCode());
        userBean.setTenentId(buildDataDto.getTenentId());
        userMapper.updateById(userBean);
//        BaseUser save = baseUserDao.save(b);
        // 判断 定位卡 门禁卡号是否重复
        checkUser(userBean.getCardNumber(), userBean.getSn(), "user", buildDataDto);

        LambdaQueryWrapper<ApiBaseLoginAccountBean> condition = new QueryWrapper<ApiBaseLoginAccountBean>().lambda()
                .eq(ApiBaseLoginAccountBean::getUserDetailId, baseUserBean.getId());
        // 账号变化或者没有账号
//        if (forceSyncCodeAsLoginAccount && (codeChanged || baseLoginAccountMapper.selectOne(condition) == null)) {
//            addOrUpdateLoginAccount(save);
//        }
//        String locateVersion = locateServerService.getLocateVersion();
        // 同步人员
        if (isApiEmployeeSyncOpen(buildDataDto)) {
//            if ("3.x".equals(locateVersion)) {
            locateServerService.apiSyncLocateUsers(Lists.newArrayList(userBean), 0, buildDataDto);
//            } else {
//                locateServerService.syncLocateUsers(Lists.newArrayList(save), 0);
//            }
        }
    }

    @Override
    public List<ApiResultData> batchAdd(List<ApiV1BaseUserAddReq> data, BuildDataDto buildDataDto) {
        List<ApiResultData> result = Lists.newArrayList();
        data.forEach(u -> {
                    ApiResultData resultData = new ApiResultData();
                    if (StringUtil.isEmpty(u.getRealName())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("人员姓名不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getRealName().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("姓名长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getGender())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("员工性别不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getGender().length() > 2) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("性别长度不能超过2字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getDepartUniqueId())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("组织唯一编码不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getDepartUniqueId().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("组织编码长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getJobUniqueId())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("岗位唯一编码不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getJobUniqueId().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("岗位编码长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getCode())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("人员工号不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getCode().length() > 10) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工号长度不能超过10字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getWorkCompany())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作单位不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (u.getWorkCompany().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作单位长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (ObjectUtil.isEmpty(u.getRole())) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("身份不能为空");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getIdCardNo()) && u.getIdCardNo().length() > 30) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("证件号长度不能超30字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getTelephone()) && u.getTelephone().length() > 13) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("电话长度不能超过13字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getCensusRegister()) && u.getCensusRegister().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("户籍所在地长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getWorkAt()) && u.getWorkAt().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("从业所在地长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getPostcode()) && u.getPostcode().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("邮编长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getAddress()) && u.getAddress().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("通讯地址长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getTitle()) && u.getTitle().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("职称/技能长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getJobDuty()) && u.getJobDuty().length() > 512) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作职责长度不能超过512字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getJobHistory()) && u.getJobHistory().length() > 512) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作经历长度不能超过512字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getEmail()) && u.getEmail().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("邮箱长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getSn()) && u.getSn().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("定位卡号长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getCardNumber()) && u.getCardNumber().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("门禁卡号长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getHighestDegree()) && u.getHighestDegree().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("最高学位长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getGraduateSchool()) && u.getGraduateSchool().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("毕业学校长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getOfficePhone()) && u.getOfficePhone().length() > 13) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("办公电话长度不能超过13字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getDuty()) && u.getDuty().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("职务长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getRemark()) && u.getRemark().length() > 512) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("备注长度不能超过512字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getUniqueId()) && u.getUniqueId().length() > 64) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("人员编码长度不能超过64字符");
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getUniqueId())) {
                        // 新增添加uniqueId
                        u.setUniqueId(SnowFlakeUtil.getUserId());
                    }
                    if (StringUtil.notEmpty(u.getSn()) && userMapper.countBySn(u.getSn(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("sn已存在");
                        result.add(resultData);
                        return;
                    }
                    if (u.getCode() != null && userMapper.countOfCode(u.getCode(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工号已存在");
                        result.add(resultData);
                        return;
                    }
                    if (userMapper.countByName(u.getRealName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("姓名已存在");
                        result.add(resultData);
                        return;
                    }
                    BaseUser b = new BaseUser();
                    BeanUtils.copyProperties(u, b);
                    b.setAddress(u.getAddress());
                    if (StringUtil.notEmpty(u.getWorkCompany())) {
//                        BpEnterpriseInfo info = infoDao.findByCompanyName(u.getWorkCompany(), Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                        ApiBpEnterpriseInfoBean info = infoMapper.findByCompanyName(u.getWorkCompany(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (info == null) {
                            resultData.setUniqueId(u.getUniqueId());
                            resultData.setName(u.getRealName());
                            resultData.setMsg("工作单位不存在");
                            result.add(resultData);
                            return;
                        }
                        b.setWorkCompanyId(info.getId());
                    }
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        if (!org.springframework.util.StringUtils.isEmpty(u.getBirthday())) {
                            b.setBirthday(sdf.parse(u.getBirthday()));
                        }
                        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                        if (u.getJoinWorkDate() != null && StringUtils.isNotBlank(u.getJoinWorkDate())) {
                            b.setJoinWorkDate(fmt.parse(u.getJoinWorkDate()));
                        }
                        if (u.getEnterDate() != null && StringUtils.isNotBlank(u.getEnterDate())) {
                            b.setEnterDate(fmt.parse(u.getEnterDate()));
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg("日期格式转换错误");
                        result.add(resultData);
                        return;
                    }
                    ApiBpJobBean job = null;
                    if (StringUtil.notEmpty(u.getJobUniqueId())) {
                        job = jobMapper.findByUniqueId(u.getJobUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (ObjectUtil.isEmpty(job)) {
                            resultData.setUniqueId(u.getUniqueId());
                            resultData.setName(u.getRealName());
                            resultData.setMsg("岗位不存在");
                            result.add(resultData);
                            return;
                        }
                        b.setJob(job.getId());
                    }
                    ApiBpDepartBean depart = null;
                    if (StringUtil.notEmpty(u.getDepartUniqueId())) {
                        depart = departMapper.findByUniqueId(u.getDepartUniqueId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (ObjectUtil.isEmpty(depart)) {
                            resultData.setUniqueId(u.getUniqueId());
                            resultData.setName(u.getRealName());
                            resultData.setMsg("组织不存在");
                            result.add(resultData);
                            return;
                        }
                        b.setDepartId(depart.getId());
                    }
                    if (u.getImage() != null) {
                        b.setIdCardImgId(u.getImage().getId());
                    }
                    if (u.getCap() != null) {
                        b.setCapId(u.getCap().getId());
                    }
                    b.setLocateSync(false);
                    if (u.getCode() == null) {
                        b.setCode(bizCodeGeneratorFacade.renYuan());
                    } else {
                        b.setCode(u.getCode());
                    }

                    //数据字典根据名称搜索如果没有则新增
                    //政治面貌
                    if (StringUtil.notEmpty(u.getPoliticallyName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("政治面貌", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getPoliticallyName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setPoliticallyId(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getPoliticallyName(), buildDataDto);
                                b.setPoliticallyId(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //民族
                    if (StringUtil.notEmpty(u.getNationName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("民族", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getNationName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setNation(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getNationName(), buildDataDto);
                                b.setNation(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //证件类型
                    if (StringUtil.notEmpty(u.getIdCardName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("身份证件类型", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getIdCardName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setIdCardType(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getIdCardName(), buildDataDto);
                                b.setIdCardType(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //健康状况
                    if (StringUtil.notEmpty(u.getHealthStatusName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("健康状况", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getHealthStatusName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setHealthStatus(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getHealthStatusName(), buildDataDto);
                                b.setHealthStatus(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //学历
                    if (StringUtil.notEmpty(u.getEducationName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("学历", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getEducationName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setEducation(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getEducationName(), buildDataDto);
                                b.setEducation(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //人员类型
                    if (StringUtil.notEmpty(u.getPersonTypeName())) {
                        ApiBaseTypeGroupItemBean bean = groupItemMapper.findByName("人员信息类型", buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BaseTypeGroup type = baseTypeGroupDao.findByName("政治面貌");
                        if (ObjectUtil.isNotEmpty(bean)) {
                            List<ApiBaseTypeGroupItemBean> list = groupItemMapper.findByNameAndTypeGroupId(u.getPersonTypeName(), bean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                            if (!CollectionUtils.isEmpty(list)) {
                                b.setPersonTypeId(list.get(0).getId());
                            } else {
                                ApiBaseTypeGroupItemBean baseTypeGroupItem = this.addItem(bean, u.getEducationName(), buildDataDto);
                                b.setPersonTypeId(baseTypeGroupItem.getId());
                            }
                        }
                    }
                    //工种不存在自动创建
                    if (StringUtil.notEmpty(u.getWorkType())) {
                        ApiBpWorkTypeBean workType = workTypeMapper.findByName(u.getWorkType(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (ObjectUtil.isNotEmpty(workType)) {
                            b.setWorkTypeId(workType.getId());
                            b.setWorkType(workType.getName());
                        } else {
                            ApiBpWorkTypeBean type = new ApiBpWorkTypeBean();
                            type.setName(u.getWorkType());
                            type.setTenentId(buildDataDto.getTenentId());
                            type.setOrgCode(buildDataDto.getOrgCode());
                            type.setStaffCount(0);
                            type.setUniqueId(Long.toString(SnowFlakeUtil.getWorktypeId()));
                            workTypeMapper.insert(type);
                            b.setWorkTypeId(type.getId());
                            b.setWorkType(type.getName());
                        }
                    }
                    // 判断 定位卡 门禁卡号是否重复
                    try {
                        this.checkUserV2(u.getCardNumber(), u.getSn(), "user", buildDataDto);
                    } catch (ApiV1ExceptionCodeMsg e) {
                        resultData.setUniqueId(u.getUniqueId());
                        resultData.setName(u.getRealName());
                        resultData.setMsg(e.getMessage());
                        result.add(resultData);
                        return;
                    }
                    //默认帽子
                    b.setCapId(1L);
                    ApiBaseUserBean saveBean = new ApiBaseUserBean();
                    BeanUtils.copyProperties(b, saveBean);
                    saveBean.setTenentId(buildDataDto.getTenentId());
                    saveBean.setOrgCode(buildDataDto.getOrgCode());
                    userMapper.insert(saveBean);

                    updateJobUserCount(job.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                    String[] certificateId = u.getCertificateIds();
                    if (certificateId != null) {
                        for (String s : certificateId) {
                            ApiBpCertificateBean one = certificateMapper.selectById(new Long(s));
                            one.setUsetId(saveBean.getId());
                            certificateMapper.updateById(one);
                        }
                    }

//                    if (forceSyncCodeAsLoginAccount) {
//                        addOrUpdateLoginAccount(save);
//                    }
                    // 新增用户添加默认角色： 员工
                    addDefaultRole4User(saveBean.getId(), buildDataDto);
                    // 同步人员
                    if (isApiEmployeeSyncOpen(buildDataDto)) {
                        locateServerService.apiSyncLocateUsers(Lists.newArrayList(saveBean), 0, buildDataDto);
                    }
                    resultData.setUniqueId(saveBean.getUniqueId());
                    resultData.setName(saveBean.getRealName());
                    resultData.setMsg("添加成功");
                    result.add(resultData);
                }
        );
        return result;
    }

    private ApiBaseTypeGroupItemBean addItem(ApiBaseTypeGroupItemBean group, String name, BuildDataDto dto) {
        ApiBaseTypeGroupItemBean item = new ApiBaseTypeGroupItemBean();
        item.setName(name);
        item.setTypeGroupId(group.getId());
        item.setTenentId(Context.getCurrentTenantId());
        item.setOrgCode(Context.getCurrentOrgCode());
        item.setShowOrder(0);
//        BeanUtils.copyProperties(bean, item);
        //拼接code
        String abbrev = group.getCode();
        String itemCode = PinYinUtils.getHanziInitials(name);
        //如果字典名称无法解析成汉语拼音则后缀用字段名称
        if (StringUtils.isNotBlank(itemCode)) {
            abbrev = abbrev + "_" + PinYinUtils.getHanziInitials(name);
        } else {
            abbrev = abbrev + "_" + name;
        }
        //字典名称如果已存在则在后面添加数字
        List<ApiBaseTypeGroupItemBean> giList = groupItemMapper.getListByCodeLike(abbrev, dto.getTenentId(), dto.getOrgCode());
        if (!CollectionUtils.isEmpty(giList)) {
            abbrev += giList.size();
        }
        item.setCode(abbrev);
        item.setState(DataStateTypes.EFFECTIVE.getState());
        groupItemMapper.insert(item);
//        BaseTypeGroupItem save = baseTypeGroupItemDao.save(item);
        checkItem(item, dto);
        return item;
    }

    private void checkItem(ApiBaseTypeGroupItemBean item, BuildDataDto dto) {
        List<ApiBaseTypeGroupItemBean> iList = groupItemMapper.findByNameAndTypeGroupId(item.getName(), item.getTypeGroupId(), dto.getTenentId(), dto.getOrgCode());
        if (iList.size() > 1) {
            throw new RuntimeException("字典名称已存在");
        }
    }

    // 每个新增用户添加默认角色： 员工
    private void addDefaultRole4User(Long userId, BuildDataDto dto) {
        ApiBaseRoleBean roleBean = roleMapper.findFirstByName(Constants.USER_DEFAULT_ROLE_NAME, dto.getTenentId(), dto.getOrgCode());
        if (roleBean != null) {
            ApiBaseRoleUserLoginRoleBean userRole = new ApiBaseRoleUserLoginRoleBean();
            userRole.setUserId(userId);
            userRole.setRoleId(roleBean.getId());
            userRole.setTenentId(dto.getTenentId());
            userRole.setOrgCode(dto.getOrgCode());
            userLoginRoleMapper.insert(userRole);
        }

    }

    private boolean isEmployeeSyncOpen() {
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_EMPLOYEE_SYNC_OPEN);
        return config == null ? false : "true".equalsIgnoreCase(config.getValue());
    }

    private void addOrUpdateLoginAccount(BaseUser save) {
        baseLoginAccountService.addOrUpdateLoginAccount(save, save.getCode(), defaultPassword);
    }

    /**
     * 判断 定位卡 门禁卡号是否重复
     *
     * @param cardNumber
     * @param sn
     */
    private void checkUser(String cardNumber, String sn, String flag, BuildDataDto dto) throws ApiV1ExceptionCodeMsg {
        List<ApiBpContractorStaffBean> staffCards = new ArrayList<>();
        List<ApiBaseUserBean> userCards = new ArrayList<>();
        List<ApiBpContractorStaffBean> staffSn = new ArrayList<>();
        List<ApiBaseUserBean> userSn = new ArrayList<>();
        if (StringUtils.isNotBlank(cardNumber)) {
            staffCards = contractorStaffMapper.findByCardNumberAndState(cardNumber, 1, dto.getTenentId(), dto.getOrgCode());
            userCards = userMapper.findByCardNumber(cardNumber, dto.getTenentId(), dto.getOrgCode());
        }
        if (StringUtils.isNotBlank(sn)) {
            staffSn = contractorStaffMapper.findBySnAndState(sn, 1, dto.getTenentId(), dto.getOrgCode());
            userSn = userMapper.findBySn(sn, dto.getTenentId(), dto.getOrgCode());
        }
        if (StringUtils.isNotBlank(flag) && flag.equals("user")) {
            if (!CollectionUtils.isEmpty(staffCards) && staffCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userCards) && userCards.size() > 1) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_USER);
            }
            if (!CollectionUtils.isEmpty(staffSn) && staffSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userSn) && userSn.size() > 1) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_USER);
            }
        } else if (StringUtils.isNotBlank(flag) && flag.equals("staff")) {
            if (!CollectionUtils.isEmpty(staffCards) && staffCards.size() > 1) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userCards) && userCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_USER);
            }
            if (!CollectionUtils.isEmpty(staffSn) && staffSn.size() > 1) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userSn) && userSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_USER);
            }
        }
    }

    private void checkUserV2(String cardNumber, String sn, String flag, BuildDataDto dto) throws ApiV1ExceptionCodeMsg {
        List<ApiBpContractorStaffBean> staffCards = new ArrayList<>();
        List<ApiBaseUserBean> userCards = new ArrayList<>();
        List<ApiBpContractorStaffBean> staffSn = new ArrayList<>();
        List<ApiBaseUserBean> userSn = new ArrayList<>();
        if (StringUtils.isNotBlank(cardNumber)) {
            staffCards = contractorStaffMapper.findByCardNumberAndState(cardNumber, 1, dto.getTenentId(), dto.getOrgCode());
            userCards = userMapper.findByCardNumber(cardNumber, dto.getTenentId(), dto.getOrgCode());
        }
        if (StringUtils.isNotBlank(sn)) {
            staffSn = contractorStaffMapper.findBySnAndState(sn, 1, dto.getTenentId(), dto.getOrgCode());
            userSn = userMapper.findBySn(sn, dto.getTenentId(), dto.getOrgCode());
        }
        if (StringUtils.isNotBlank(flag) && flag.equals("user")) {
            if (!CollectionUtils.isEmpty(staffCards) && staffCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userCards) && userCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_USER);
            }
            if (!CollectionUtils.isEmpty(staffSn) && staffSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userSn) && userSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_USER);
            }
        } else if (StringUtils.isNotBlank(flag) && flag.equals("staff")) {
            if (!CollectionUtils.isEmpty(staffCards) && staffCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userCards) && userCards.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_CARDNUMBER_USED_BY_USER);
            }
            if (!CollectionUtils.isEmpty(staffSn) && staffSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userSn) && userSn.size() > 0) {
                throw new ApiV1ExceptionCodeMsg(Status.API_V1_SN_USED_BY_USER);
            }
        }
    }

    /**
     * @param jobId
     */
    protected void updateJobUserCount(Long jobId, Long tenentId, String orgCode) {
        jobMapper.updateJobUserCount(jobId, tenentId, orgCode);
//        jobDao.updateJobUserCount(jobId);
    }
}
